<?php


namespace App\Model\Logic;


use App\Helper\RedisConst;
use App\Model\Entity\EnteredBrand;
use App\Model\Entity\FollowNum;
use App\Model\Entity\MemberExtends;
use App\Model\Entity\Members;
use App\Model\Entity\MemberVapeDevice;
use App\Model\Entity\Shops;
use Swoft\Bean\Annotation\Mapping\Bean;
use Swoft\Bean\Annotation\Mapping\Inject;
use Swoft\Redis\Pool;

/**
 * @Bean()
 * Class MemberRedisLogic
 * @package App\Model\Logic
 */
class MemberRedisLogic
{

    /**
     * @Inject("redis1.pool")
     * @var Pool
     */
    private $redis;

    /**
     * @Inject()
     * @var CountryLogic
     */
    private $country_logic;

    public function info($member_id)
    {
        $data = $this->redis->hGetAll(RedisConst::MEMBER . $member_id);
        if($data) return $data;
        //重新构建redis数据
        $data = $this->buildInfo($member_id);
        return $data;
    }


    /**
     * 构建用户redis信息
     * @param $member_id
     * @return array
     * @throws \ReflectionException
     * @throws \Swoft\Bean\Exception\ContainerException
     * @throws \Swoft\Db\Exception\DbException
     */
    public function buildInfo($member_id)
    {
        $condition = ['member_id' => $member_id] ;
        $base = Members::find($member_id);
        if(!$base) return [];
        $extends = MemberExtends::where($condition)->first()->getModelOriginal();
        if(!$extends) return [];
        $follow = FollowNum::where($condition)->first()->getModelOriginal();
        $vape = MemberVapeDevice::where($condition)->get(['status','brand_id','model_id'])->toArray();
        $data = [
            'id' => $base->getId(),
            'nickname' => $base->getNickname(),
            'email'  => $base->getEmail(),
            'avatar' => $base->getAvatar(),
            'sys_avatar' => $base->getSysAvatar(),
            'displayname' => $base->getDisplayname(),
            'profile' => $base->getProfile(),
            'reg_id' => $base->getRegIp(),
            'level' => $base->getLevel(),
            'nation' => ($base->getNation() > 0) ? $base->getNation() : -1,
            'nation_name' => $this->country_logic->getName($base->getNation()),
            'gender' => $base->getGender(),
            'status' => $base->getStatus(),
            'is_verify' => $base->getIsVerify(),
            'created_at' => $base->getCreatedAt(),
            'birthday' => $base->getBirthday(),
            'score' => (int) $extends['score'],
            'reported_times' => $extends['reported_times'],
            'posts_num' => (int)$extends['posts_num'],
            'review_num' => (int)$extends['review_num'],
            'lang_setting' => $extends['lang_setting'],
            'reg_equipment' => intval($extends['equipment']),
            'refuse' => $extends['refuse'],
            'cover_name' => $base->getCoverName(),
            'fans_num'   => isset($follow['fans_num']) ? $follow['fans_num'] : 0,
            'follow_num' => isset($follow['follow_num']) ? $follow['follow_num'] : 0,
            'vape_device' => $vape ? serialize($vape) : '',
            'website' => $extends['website'] ? $extends['website'] : '',
            'youtube' => $extends['youtube'] ? $extends['youtube'] : '',
            'youtube_verify' => is_numeric($extends['youtube_verify']) ? intval($extends['youtube_verify']) : 3,
            "review_permission" => $extends['review_permission'],
            "type" => intval($base->getType()),
            "type_id" => intval($base->getTypeId()),
            "is_update_birthday" => intval($base->getIsUpdateBirthday()),
            "uuid" => $base->getUuid() ? $base->getUuid() : $this->initUUID($member_id),
        ];
        $data['member_uuid'] = $data['uuid'];
        //机器人的follow数特殊处理
        if($extends['is_import']){
            $robot = $this->_robotFollowNum($data['fans_num'], $data['follow_num']);
            $data['fans_num'] = $robot['fans_num'];
            $data['follow_num'] = $robot['follow_num'];
        }
        //如果是商业账户 头像处理
        if($base->getType() != 1){
            $data['avatar'] = $this->businessAccountAvatar($base->getTypeId(), $base->getType());
        }
        $this->redis->hMSet(RedisConst::MEMBER . $member_id, $data);
        return $data;
    }

    public function businessAccountAvatar($business_id, $type)
    {
        if($type == 2){
            //brand
            $brand = EnteredBrand::find($business_id);
            return $brand->getLogo();
        }
        if($type == 3){
            //shop
            $shop = Shops::find($business_id);
            return $shop->getCover();
        }
    }


    //随机处理机器粉的follow following
    private function _robotFollowNum($fans_num, $follow_num)
    {
        $data = [
            'fans_num' => $this->_randFansNum($fans_num),
            'follow_num' => $this->_randFollowingNum($follow_num),
        ];
        return $data;
    }

    //随机粉丝num
    private function _randFansNum($number)
    {
        if($number > 200) return $number;
        return rand(110, 200);
    }

    //随机following num
    private function _randFollowingNum($number)
    {
        if($number > 500) return $number;
        return rand(200, 300);
    }


    /**
     * 创建uuid
     * @param $member_id
     * @return string
     * @throws \ReflectionException
     * @throws \Swoft\Bean\Exception\ContainerException
     * @throws \Swoft\Db\Exception\DbException
     */
    public function initUUID($member_id)
    {
        $uuid = UUID();
        Members::where('id', $member_id)->where('uuid', '0')->update([ 'uuid' => $uuid ]);
        return $uuid;
    }

}